PHP Get User Real IP Address | PHP Function to Retrieve IP Address

Learn how to use a PHP function to retrieve the real IP address of a user visiting your website. Use this code snippet to accurately track and analyze user activity.

<?php

function get_user_ip() {
	if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
		return $ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
		return $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} else {
		return $ip = $_SERVER['REMOTE_ADDR'];
	}
}

echo get_user_ip();

?>